<?php


/**
 * 活动Action
 * Enter description here ...
 * @author Administrator
 *
 */
class ActivityAction extends CommonAction{
	
	/**
	 * 活动列表
	 * Enter description here ...
	 * 启用状态：1 禁用状态：0
	 */
	public function index() {
		$activity = D('Activity'); 
		
		import("@.ORG.Page"); //导入分页类
		
		$count = $activity->count();    //计算总数
		$p = new Page ($count,10);
		$activitydata=$activity->limit($p->firstRow.','.$p->listRows)->order('id desc')->findAll();
		
		$page = $p->show ();
		$this->assign("page",$page);   //分页信息
		$this->assign("activitydata",$activitydata);  //查询数据
		
		$this->display();
	}
	
	
	
	/**
	 * 添加
	 * @see CommonAction::add()
	 */
	public function add(){
		
		parent::add();  //调用父类方法
	}
	
	
	
	/**
	 * 保存活动确认
	 * @see CommonAction::insert()
	 */
	public function insert(){
		Log::write("....开始保存活动..",Log::DEBUG);
		$data = Init_GP(array('title','url','starttime','endtime','memo','state'));   //页面参数
		
		$activity = D('Activity'); 
		$accessory = A('Accessory');
		
		if(empty($_FILES)){   //
			$this->error('必须选择上传文件');
			
		}else{
			$a=$accessory->upFile('Activity');  //先上传文件返回结果信息
			if(isset($a)){  
				$data['image']=$a[0]['savename'];   //保存文件名称
				
				$data = $activity->create($data);
				if(empty($data) || $data === false) {
					$this->error($activity->getError());
				}
				
				
				$data['starttime'] = strtotime($data['starttime']);   //转换时间
				$data['endtime'] = strtotime($data['endtime']); 
				
				$id = $activity->add($data);  //保存
				
				if($id){ //保存成功
					$this->assign('jumpUrl','__URL__/index');
					$this->success("添加成功");
				}else {
					//失败提示
					$this->error($activity->getError());
				}
			}else{
				$this->error('上传文件有异常请与系统管理员联系');
			}
		}
		
		Log::write("....保存活动完成..",Log::DEBUG);
	}
	
	
	
	
	
	/**
	 * 修改
	 * @see CommonAction::edit()
	 */
	public function edit(){
		$activity = D('Activity'); 
		$id     = GetNum($_GET['id']);   //主键
		$vo	=	$activity->find($id);
		
		$this->assign('data',$vo);
		
		$this->display();
	}
	
	
	
	/**
	 * 修改确认
	 * @see CommonAction::update()
	 */
	public function update(){
		$id = GetNum($_POST['id']);  //主键ID
		$awhere['id'] = $id;
		$data = Init_GP(array('title','url','starttime','endtime','memo','state'));
		
		$activity = D('Activity'); 
		$accessory = A('Accessory');
		
		/**
		 * 保证每条活动商品都有图片
		 * 修改：修改的记录已经没有图片了则必须上传图片，如果还存在图片则没有必要强制要图片
		 */
		
		$obj = $activity->where("id=$id")->Field("image")->select(); 
		$imageName = $obj[0]['image'];
		
		Log::write("..活动图片路径..:" . $imageName,Log::DEBUG);
		if(!empty($imageName)){
			Log::write("..修改活动记录存在活动图片!..:" ,Log::DEBUG);
			
			$obj["title"] = $data["title"];	
			$obj["url"] = $data["url"];	
			$obj["starttime"] = strtotime($data["starttime"]);	
			$obj["endtime"] = strtotime($data["endtime"]);	
			$obj["memo"] = $data["memo"];	
			$obj["state"] = $data["state"];	
		
				
			$st = $activity ->where("id=$id")->save($obj);  //更新记录	
			
			if($st){
				$this->assign('jumpUrl','__URL__/index');     //跳转到列表首页
				$this->success("修改成功");
				
			}else{
				$this->error('修改失败！');
			}
			
		}else{
			Log::write("..修改活动记录不存在活动图片!..:" ,Log::DEBUG);
			
				if(empty($_FILES)){   // 判断是否存在图片
					$this->error('必须选择上传文件');
				}else{
					$a=$accessory->upFile('Activity');  //先上传文件返回结果信息
					
					if(isset($a)){  
						$obj['image']=$a[0]['savename'];   //保存文件名称
						
						$obj["title"] = $data["title"];	
						$obj["url"] = $data["url"];	
						$obj["starttime"] = strtotime($data["starttime"]);	
						$obj["endtime"] = strtotime($data["endtime"]);	
						$obj["memo"] = $data["memo"];	
						$obj["state"] = $data["state"];	
						
						$st = $activity ->where("id=$id")->save($obj);  //更新记录	
						
						if($st){ //修改成功
							$this->assign('jumpUrl','__URL__/index');
							$this->success("修改成功");
						}else {  //失败提示
							$this->error('修改失败！');
						}
					}else{
						$this->error('上传文件有异常请与系统管理员联系');
					}
				}
		
				
			
		}
		
		
	}
	
	
	
	
	
	
	/**
	 * 删除（单条）
	 * @see CommonAction::del()
	 */
	public function del(){
		$id = GetNum($_GET['id']);  //主键
		//Log::write("...删除单条活动..:" . $id);
		
		$activity = D('Activity'); 
		//$obj  = $activity->find($id); //获取对象
		
		$obj = $activity->where("id=$id")->Field("image")->select();   //获取数组形式
		
		$imageName = $obj[0]['image'];
		
		$fullpath = UPLOADIMGEEXTEND.'Activity/' .$imageName ;
		
		//Log::write("..活动图片路径..:" . $fullpath);
		
		$st = $activity->where("id=$id")->delete();
		if($st){
			@unlink($fullpath);    //删除图片附件
			
			$this->assign('jumpUrl','__URL__/index');     //跳转到列表首页
			$this->success("删除成功");
			
		}else{
			$this->error('删除失败！');
		}
		
		
	}
	
	
	
	
	/**
	 * 删除（多条）
	 * @see CommonAction::del()
	 */
	public function dels(){
		$data = Init_GP(array('ids'));    //参数
		$ids = $data['ids'];  //多个主键
		
		$activity = D('Activity'); 
		
		$prefix = C('DB_PREFIX');   //数据库前缀
		 if(!empty($activity)) {
            $ids       = getdotstring($ids,'int');  //字符串分割
            
            //Log::write("...删除多条活动..:" . $ids);
            	
            $objs = $activity->where("id in ($ids)")->Field("image")->select();  //现获取删除记录上图片
            	
            $sql = "DELETE U FROM `{$prefix}activity` as U  WHERE U.id in({$ids})";   //删除多条记录
            $st = $activity->execute($sql) ;
            if ($st){

            	if(!empty($objs)){  //循环数组删除图片
            		foreach($objs as $key => $value){
            			//Log::write(" ...删除图片路径:..  " .$value['image']);
            			$fullpath = null ;
            			$fullpath = UPLOADIMGEEXTEND.'Activity/' .$value['image'] ;
            			
            			@unlink($fullpath);    //删除图片附件
            		}
            	}
            	
            	$this->success('已删除选定项');
            }else{
            	$this->error($activity->getError());
            }
        }
		
	}
	
	
	
	/**
	 * 删除图片
	 * Enter description here ...
	 */
	public function delImg(){
		$id = GetNum($_GET['id']);   //活动主键
		
		if(!empty($id)){
			$model = M('Activity');
			
			$obj = $model->find($id);  //获取活动对象
			$imageName = $obj['image'];   //活动图片  
			
			$obj['image'] = '';
			$st = $model->save($obj);    //置空图片
			// $model->where("id=$id")->setField('image','');   //活动图片设置空
			
			if(!empty($st)){   
				//...更新记录成功后删除物理文件
				$fullpath = UPLOADIMGEEXTEND.'Activity/' .$imageName ;
				
				@unlink($fullpath);    //删除文件
				
				$data['state']= "success";
				echo json_encode($data);
			}else {
				$data['state']= "error";
				echo json_encode($data);
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	/**
	 * 调用TP中文件上传
	 * Enter description here ...
	 */
	/*
	private function upFile(){
		Log::write(".......开始上传图片.......",Log::DEBUG);
		
		import('@.Org.UploadFile');
		$upload=new UploadFile();
		
		$upload->maxSize='3292200';  //是指上传文件的大小，默认为-1,不限制上传文件大小bytes
		$upload->savePath=UPLOADIMGEEXTEND.'Activity/';     // __ROOT__."/Public/accessory/upload/Activity";
		
		$upload->saveRule=uniqid;    //上传文件的文件名保存规则  time uniqid  com_create_guid  uniqid
		$upload->uploadReplace=true;     //如果存在同名文件是否进行覆盖
		$upload->allowExts=array('jpg','jpeg','png','gif');     //准许上传的文件后缀
		$upload->allowTypes=array('image/png','image/jpg','image/pjpeg','image/gif','image/jpeg');  //检测mime类型
		$upload->thumb=false;   //是否开启图片文件缩略
		$upload->thumbMaxWidth='300,500';  //以字串格式来传，如果你希望有多个，那就在此处，用,分格，写上多个最大宽
		$upload->thumbMaxHeight='200,400';	//最大高度
		$upload->thumbPrefix='s_,m_';//缩略图文件前缀。小图或中途
		$upload->thumbRemoveOrigin=false;  //如果生成缩略图，是否删除原图
		
		if($upload->upload()){
			//局部变量，你可以在此处，保存到一个超全局变量当中去进行返回
			$info=$upload->getUploadFileInfo();
			//Log::write(".......上传图片完毕.......",Log::DEBUG);
					
			return $info;
		}else{
			//是专门来获取上传的错误信息的
			$this->error($upload->getErrorMsg());
		}
			
	}
		
	*/	
		
	
	
	
	
	
	
	
	
}
?>